package com.example.shushiyunsst.fragment.main.home.child

import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.normalShortToast
import com.example.library_common.view.web_view.JssAdvancedWebView
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.bean.NewsDetailBean

class NewsDetailFragment : BaseFragmentEx(),JssAdvancedWebView.Listener {

    companion object {
        fun newInstance(nid: String): NewsDetailFragment {
            val args = Bundle()
            args.putString("nid", nid)
            val fragment = NewsDetailFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var nid: String = ""

    private var mToolbar: Toolbar?=null

    private var mJssAdvancedWebView: JssAdvancedWebView?=null

    private var mProgressBar: ProgressBar?=null

    private var mReloading: TextView?=null

    private var isReady = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        nid = arguments?.getString("nid") ?: ""
    }

    override fun getLayoutId(): Any {
        return R.layout.news_detail_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mToolbar=view.findViewById(R.id.mToolbar)

        mJssAdvancedWebView=view.findViewById(R.id.mWebView)

        mProgressBar=view.findViewById(R.id.mProgressBar)

        mReloading=view.findViewById(R.id.mReloading)

        mToolbar?.setNavigationOnClickListener { onBackPressedSupport() }

        initWebView()

        mReloading?.setOnClickListener {
            netQuest()
        }

        mReloading?.performClick()
    }

    private fun initWebView() {
        mJssAdvancedWebView?.setListener(this, this)

        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            val settings = mJssAdvancedWebView?.settings
            settings?.cacheMode = WebSettings.LOAD_NO_CACHE
            settings?.domStorageEnabled = true
            settings?.javaScriptEnabled = true
            settings?.blockNetworkImage = false
            settings?.javaScriptCanOpenWindowsAutomatically = true
            settings?.loadsImagesAutomatically = true
            settings?.allowFileAccess = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                settings?.allowUniversalAccessFromFileURLs = true
                settings?.allowFileAccessFromFileURLs = true
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
        }

        mJssAdvancedWebView?.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    mProgressBar?.visibility = View.GONE
                } else {
                    mProgressBar?.visibility = View.VISIBLE
                    mProgressBar?.progress = newProgress
                }
            }
        }

        mJssAdvancedWebView?.webViewClient = object : WebViewClient() {

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                isReady = false
                mProgressBar?.visibility = View.VISIBLE
                mProgressBar?.progress = 0
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                isReady = true

            }
        }
    }


    override fun onSupportVisible() {
        super.onSupportVisible()
        mJssAdvancedWebView?.onResume()
    }


    override fun onResume() {
        super.onResume()
        mJssAdvancedWebView?.onResume()
    }


    override fun onPause() {
        super.onPause()
        mJssAdvancedWebView?.onPause()

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    override fun onDestroy() {
        super.onDestroy()

        mJssAdvancedWebView?.webChromeClient = null

        mJssAdvancedWebView?.onDestroy()
    }



    private fun netQuest() {
        RestClient.builder()
            .url(R.string.queryIndexNewsByNid)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "nid" to nid
                    )
                )
            )
            .success {
                mReloading?.visibility=View.GONE
                parseData(it)
            }
            .failure {
                mReloading?.visibility=View.VISIBLE
                normalShortToast(_mActivity,R.string.net_work_failed)
//                Toast.makeText(_mActivity, "网络异常", Toast.LENGTH_SHORT).show()
            }
            .error { _, msg ->
                mReloading?.visibility=View.VISIBLE
                normalShortToast(_mActivity,msg)
//                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build().post()
    }

    private fun parseData(it: String?) {
        val obj = JSON.parseObject(it)
        val news = obj["news"].toString()
        val mBean = JSON.parseObject(news, NewsDetailBean::class.java)
        mToolbar?.title=mBean.title
        mJssAdvancedWebView?.loadDataWithBaseURL(null, mBean.contentDesc, "text/html", "utf-8", null)
    }

    override fun onPageStarted(url: String?, favicon: Bitmap?) {

    }

    override fun onPageFinished(url: String?) {

    }

    override fun onPageError(errorCode: Int, description: String?, failingUrl: String?) {
        mReloading?.visibility = View.VISIBLE
    }

    override fun onDownloadRequested(
        url: String?,
        suggestedFilename: String?,
        mimeType: String?,
        contentLength: Long,
        contentDisposition: String?,
        userAgent: String?
    ) {

    }

    override fun onExternalPageRequest(url: String?) {

    }
}